package pers.wq;

import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import pers.wq.model.ClassModel;
import pers.wq.model.bean.ModelBean;
import pers.wq.util.Helper;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class BaseController extends ActionSupport{
	public static final String JSON = "json";
	public static final String DEFAULT_SUC_MSG = "请求成功";
	public static final String DEFAULT_ERR_MSG = "请求失败";
	public static final String SESSION_LOGIN_KEY = "login";
	public static final String CAT_XML = "category.xml";
	public static final String CAT_SUPERADMIN = "superadmin";
	public static final String CAT_TEACHER = "teacher";
	public static final String CAT_STUDENT = "student";
	public static final String MAP_IDKEY = "idKey";
	public static final String MAP_TABLE = "tableName";
	
	private String jsonResult;
	private BaseControllerData bcd;
	
	public BaseController(){
		
	}
	public String scheduleSelect(){
		Map map = (Map)getSessionLogin();
		String user = map.get("user").toString();
		String catId = map.get("catId").toString();
		String table = catId.equals("teacher")?"rpt,room,project":"rpt,room,srpt,project";
		catId = catId.equals("teacher")?"rpt.tid="+user:"srpt.sid="+user + " AND srpt.rptid=rpt.rptid";
		return this.easyJson(BaseModel.select("room.rname as rname,rpt.time as time,project.pname as pname", table, catId+" AND rpt.rid=room.rid AND rpt.pid=project.pid", null, null));
	}
	public String classSelect(){
		ClassModel cm = new ClassModel();
		return this.easyJson(cm.select("cid as id,cname as name", null, "cid", null));
	}
	public String roomSelect(){
		return this.easyJson(BaseModel.select("rid as id,rname as name", "room", null, "rid", null));
	}
	public String genderSelect(){
		return this.easyJson(BaseModel.select("id,name", "gender", null, "id", null));
	}
	public String studentSelect(){
		return this.easyJson(BaseModel.select("sid as id,sname as name", "student", null, "sid", null));
	}
	public String teacherSelect(){
		return this.easyJson(BaseModel.select("tid as id,tname as name", "teacher", null, "tid", null));
	}
	public String attendanceSelect(){
		return this.easyJson(BaseModel.select("aid as id,aname as name", "attendance", null, "aid", null));
	}
	public String projectSelect(){
		return this.easyJson(BaseModel.select("pid as id,pname as name", "project", null, "pid", null));
	}
	public String rptSelect(){
		return this.easyJson(BaseModel.select("rptid as id,concat('[',rname,'][',pname,'][',time,'][',tname,']') as name", "rpt,room,project,teacher", "rpt.rid=room.rid and rpt.pid=project.pid and rpt.tid=teacher.tid", "rpt.pid", null));
	}
	public String update(){
		Map<String, Object> map = request2Map(ServletActionContext.getRequest());
		String tableName = (String) map.get(MAP_TABLE);
		String idKey = (String) map.get(MAP_IDKEY);
		String id = map.get(idKey).toString();
		map.remove(MAP_TABLE);
		map.remove(MAP_IDKEY);
		map.remove(idKey);
		boolean b = BaseModel.update(tableName, map, idKey + "=" + id);
		return this.easyJson(b);
	}
	public String delete(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String idKey = request.getParameter(MAP_IDKEY);
		String id =  request.getParameter(idKey);
		boolean b = BaseModel.delete(request.getParameter(MAP_TABLE),idKey + "=" + id);
		return this.easyJson(b);
	}
	protected  Map<String,Object> request2Map(HttpServletRequest request){
		Map<String,Object> map = new HashMap();
		Enumeration<String> e = request.getParameterNames();
		String key;
		while(e.hasMoreElements()){
			key = e.nextElement();
			map.put(key, request.getParameter(key));
		}
		return map;
	}
	public String insert(){
		Map<String, Object> map = request2Map(ServletActionContext.getRequest());
		String tableName = (String) map.get(MAP_TABLE);
		map.remove(MAP_TABLE);
		boolean b = BaseModel.insert(tableName, map);
		return this.easyJson(b?b:null);
	}
	protected Map<String,Object> mkControllerMap(String xml,String tableid,String idKey){
		Map<String,Object> map = new HashMap();
		ModelBean mb = (ModelBean) loadBean(xml,tableid);
		map.put("tableController", mb.toMap());
		String table = mb.getTable() == null ? tableid : mb.getTable();
		map.put("tableData", BaseModel.select(mb.getColumns(), table, mb.getCondition(), mb.getOrder(), mb.getLimit()));
		map.put("action", tableid);
		map.put(MAP_IDKEY, idKey);
		return map;
	}
	protected Map<String,Object> mkInput(Map<String,Object> map){
		Map<String,Object> reMap = new HashMap();
		reMap.put("inMap", new HashMap());
		Iterator<String> iterator = map.keySet().iterator();
		String key;
		while(iterator.hasNext()){
			key = iterator.next();
			switch(key){
			case "idKey":
			case "tableName":reMap.put(key, map.get(key));break;
			default : ((Map) reMap.get("inMap")).put(key,map.get(key));break;
			}
		}
		return reMap;
	}
	protected String login(LoginModel user,String cat_id){
		Map<String,Object> map = new HashMap();
		if(user.login()){
			this.loadBaseData(cat_id);
			map.put("cats",this.getBcd().getCatMap());
			map.put("user",user);
			map.put("catId", cat_id);
			setSessionLogin(map);
		}
		return this.easyJson(user.login() ? map : null);
	}
	protected void loadBaseData(String catId){
		ApplicationContext factory = new ClassPathXmlApplicationContext(CAT_XML);
		setBcd((BaseControllerData) factory.getBean(catId));
	}
	protected Object loadBean(String xml,String id){
		ApplicationContext factory = new ClassPathXmlApplicationContext(xml);
		return  factory.getBean(id);
	}
	public String checkLogin(){
		return this.easyJson(this.containSession(SESSION_LOGIN_KEY) ? getSessionLogin() : null);
	}
	
	protected String easyJson(Object data){
		return easyJson(data,DEFAULT_SUC_MSG,DEFAULT_ERR_MSG);
	}
	
	protected String easyJson(Object data,String sucMsg,String errMsg){
		if(null != data){
			return sucJson(data,sucMsg);
		}else{
			return errJson(errMsg);
		}
	}
	
	protected String sucJson(Object data,String msg){
		return showJson(200,data,msg);
	}
	
	protected String errJson(String msg){
		return showJson(400,null,msg);
	}
	
	
	protected String showJson(int code,Object data,String msg){
		Map<String,Object> jsonMap = new HashMap();
		jsonMap.put("code", code);
		jsonMap.put("msg", msg);
		jsonMap.put("data", data);
		setJsonResult(Helper.json_encode(jsonMap));
		return JSON;
	}
	public static boolean containSession(String key) {
		return ActionContext.getContext().getSession().containsKey(key);
	}
	public static Object getSessionLogin(){
		return ActionContext.getContext().getSession().get(SESSION_LOGIN_KEY);
	}
	public static void setSessionLogin(Object obj){
		ActionContext.getContext().getSession().put(SESSION_LOGIN_KEY,obj);
	}
	public String index(){
		return SUCCESS;
	}

	public String getJsonResult() {
		return jsonResult;
	}

	public void setJsonResult(String jsonResult) {
		
		this.jsonResult = jsonResult;
		//System.out.println("setJsonResult" + this.jsonResult);
	}

	public BaseControllerData getBcd() {
		return bcd;
	}

	public void setBcd(BaseControllerData bcd) {
		this.bcd = bcd;
	}
	
	
}
